<?php

require_once("Dimension1.php");
require_once("Dimension2.php");
require_once("Dimension2Manager.php");
require_once("Dimension4Manager.php");

class Dimension1Manager {

    public function add(Dimension1 $d1) {
        $q = $this->_db->prepare('INSERT INTO Dimension1 VALUES (:refD1,:nom)');
        $q->bindValue(':nom', $d1->getNom());
        $q->bindValue(':refD1', $d1->getRefD1());
        $q->execute();
    }

    public function count() {
        return $this->_db->query('SELECT COUNT(*) FROM Dimension1')->fetchColumn();
    }

    public function delete(Dimension1 $d1) {
        $exec = $this->_db->exec("DELETE FROM Dimension1 WHERE refD1 = '" . $d1->getRefD1() . "'");
        return $exec;
    }

    public static function get($refD1) {
      
        $pdo = PDO2::getInstance();
        $requete = $pdo->prepare("SELECT refD1, nom FROM Dimension1 WHERE refD1 = :refD1");
        $requete->bindValue(':refD1',$refD1);
        $requete->execute();
        
        $donnees = $requete->fetch(PDO::FETCH_ASSOC);
        
        $dimension1 = new Dimension1($donnees);
        $lesD2 = self::getDimension2($dimension1);
        $dimension1->addDimension2($lesD2);

        return $dimension1;
    }

    public static function getList() {
        $pdo = PDO2::getInstance();

        $tmp = array();
        $dimension1 = array();

        $requete = $pdo->prepare('SELECT refD1, nom FROM Dimension1');
        $requete->execute();

        while ($donnees = $requete->fetch(PDO::FETCH_ASSOC)) {
            $tmp[] = new Dimension1($donnees);
        }
        foreach ($tmp as $d1) {
            $lesD2 = Dimension1Manager::getDimension2($d1);
            $d1->addDimension2($lesD2);
            $dimension1[] = $d1;
        }

        return $dimension1;
    }

    /**
     * Retourne les Dimension2 associées à 1 Dimension1
     * @param type $refD1
     * @return type 
     */
    public static function getDimension2(Dimension1 $dim1) {
        $pdo = PDO2::getInstance();
        $requete = $pdo->prepare("SELECT refD2, d2.refD1, titre, descr FROM Dimension2 d2, Dimension1 d1 where d2.refD1 = d1.refD1 and d2.refD1 = :refD1");
        $requete->bindValue(':refD1', $dim1->getRefD1());

        $requete->execute();
        $d1 = $dim1;

        while ($lignes = $requete->fetch(PDO::FETCH_OBJ)) {
            $d2 = new Dimension2($d1, $lignes->refD2, $lignes->titre, $lignes->descr);
            $d2->addDimension3(Dimension2Manager::getDimension3($d2));
            $d2->addDimension4(Dimension4Manager::getList($d2));
            
            $d1->addDimension2($d2);
        }
        return $d1->getLesDimensions2();
    }

    public function setDb(PDO $db) {
        $this->_db = $db;
    }

}

?>